package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/go-test/service"
	"net/http"
	"strconv"
	"github.com/go-test/model"
	"log"
)

func GetUser(c *gin.Context) {
	respMap := make(map[string]interface{})

	id, _ := strconv.Atoi(c.Param("id"))
	user := service.GetUserById(id)
	respMap["user"] = user;

	c1 := make(chan *model.Role)
	c2 := make(chan *model.Dept)
	if user != nil {
		roleId, _ := strconv.Atoi(user.Roleid)
		go func() {
			role := service.GetRoleById(roleId)
			c1 <- role
		}()
		go func() {
			dept := service.GetDepById(user.Deptid)
			c2 <- dept
		}()
	}

	for i := 0; i < 2; i++ {
		select {
		case msg1 := <-c1:
			respMap["role"] = msg1;
		case msg2 := <-c2:
			respMap["dept"] = msg2;
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  "posted",
		"message": "ok",
		"data":    respMap,
	})
}

func SaveUser(c *gin.Context) {
	log.Println("请求保存用户接口")
	var user *model.User;
	if c.BindJSON(&user) == nil {
		service.SaveUser(user)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  "posted",
		"message": "ok",
		"data":    user,
	})
}

func UpdateUser(c *gin.Context) {
	log.Println("请求更新用户接口")
	var user *model.User;
	if c.BindJSON(&user) == nil {
		service.UpdateUser(user)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  "posted",
		"message": "ok",
		"data":    user,
	})
}

func DeleteUser(c *gin.Context) {
	user := new(model.User);
	id, _ := strconv.Atoi(c.Param("id"))
	log.Println("请求删除用户接口，id:", id)
	user.Id = id;
	service.DeleteUser(user)
	c.JSON(http.StatusOK, gin.H{
		"status":  "posted",
		"message": "ok",
		"data":    nil,
	})
}